package cn.tnar.yunpark.careyes.nbiot;

import cn.tnar.yunpark.careyes.CarEyesUtil;
import cn.tnar.yunpark.careyes.nbiot.model.HeartBeat;
import cn.tnar.yunpark.careyes.nbiot.model.Message;
import cn.tnar.yunpark.careyes.nbiot.model.NBStatus;
import cn.tnar.yunpark.model.SpaceSensorStatus;
import cn.tnar.yunpark.model.SpaceStatus;
import cn.tnar.yunpark.service.SensorEventDispatcher;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


/**
 * author : CaineZhu
 * date   : 2017/12/22
 * desc   : logic handler
 */


public class CarEyesNBMessageHandler extends SimpleChannelInboundHandler<Message> {

    Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    private SensorEventDispatcher dispatcher;
    private static final DateFormat LBM_DATA_TIME = new SimpleDateFormat("yyyyMMddHHmmss");

    public CarEyesNBMessageHandler(SensorEventDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, Message obj) throws Exception {
        if (obj instanceof NBStatus) {
            NBStatus msg = (NBStatus) obj;
            logger.info("handler receiver:{}", msg);
            Calendar calendar = Calendar.getInstance();
            calendar.set(msg.getYear() + 2000, msg.getMonth() - 1, msg.getDay(), msg.getHour(), msg.getMinutes(), msg.getSecond());
            String dateTime = LBM_DATA_TIME.format(calendar.getTime());
            SpaceStatus event = new SpaceStatus(msg.getSensorId(), CarEyesUtil.toLbmStatus(msg.getStatus()), dateTime);
            dispatcher.dispatch(event);
        } else if (obj instanceof HeartBeat) {
            HeartBeat msg = (HeartBeat) obj;
            logger.info("handler receiver:{}", msg);
            SpaceSensorStatus sensorStatus = new SpaceSensorStatus(msg.getSensorId(), msg.getVbattery(), String.valueOf(msg.getVbattery()),
                    msg.getCsq(), String.valueOf(msg.getCsq()));
            dispatcher.dispatch(sensorStatus);
        }

    }
}
